<?php

/**
 * Less class
 *
 * @author Julot
 * @since Friday, June 1, 2012. 02:18 PM
 */
Yii::import('ext.less.components.LessCompiler');

class Less extends LessCompiler {

	public function init() {
		// Set basePath to application if not defined.
		if (!isset($this->basePath)) {
			$this->basePath = Yii::getPathOfAlias('application');
		}
		parent::init();
		$this->touch();
	}

	protected $_hasChanges = null;

	protected function hasChanges() {
		if (!isset($this->_hasChanges)) {
			$dirs = array();
			foreach ($this->paths as $source=>$destination) {
				// The original didn't include basePath in check
				$destination = "$this->basePath/$destination";
				$source = "$this->basePath/$source";
				$compiled = $this->getLastModified($destination);
				if (!isset($lastCompiled) || $compiled < $lastCompiled) {
					$lastCompiled = $compiled;
				}

				if (!in_array(dirname($source), $dirs)) {
					$dirs[] = $source;
				}
			}

			foreach ($dirs as $dir) {
				$modified = $this->getLastModified($dir);
				// The original $modified < $lastModified
				if (!isset($lastModified) || $modified > $lastModified) {
					$lastModified = $modified;
				}
			}

			$this->_hasChanges = isset($lastCompiled) && isset($lastModified) &&
				$lastModified > $lastCompiled;
		}
		return $this->_hasChanges;
	}

	public $touchPaths = array();
	
	public function touch() {
		if ($this->hasChanges()) {
			foreach ($this->touchPaths as $path) {
				touch("$this->basePath/$path");
			}
		}
	}

}
